package com.atguigu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2022/7/18 11:23
 */
public class Dwd_01_BaseLogApp extends BaseAppV1 {
    
    private final String START = "start";
    private final String DISPLAY = "display";
    private final String ERR = "err";
    private final String PAGE = "page";
    private final String ACTION = "action";
    
    public static void main(String[] args) {
        new Dwd_01_BaseLogApp().init(
            3001,
            2,
            "Dwd_01_BaseLogApp",
            Constant.TOPIC_ODS_LOG
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. etl
        SingleOutputStreamOperator<JSONObject> etledStream = etl(stream);
        // 2. 纠正新老客户
        SingleOutputStreamOperator<JSONObject> validatedStream = validateNewOrOld(etledStream);
        
        // 3. 分流
        Map<String, DataStream<String>> fiveStreams = splitStream(validatedStream);
   
        
        // 4. 不同的流写入到不同的Topic
        writeToKafka(fiveStreams);
    }
    
    private void writeToKafka(Map<String, DataStream<String>> streams) {
        streams.get(START).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        streams.get(DISPLAY).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(ERR).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(PAGE).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(ACTION).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
    }
    
    private Map<String, DataStream<String>> splitStream(SingleOutputStreamOperator<JSONObject> stream) {
        /*
        5个流: 启动  主流
               页面  侧输出流
               曝光
               错误
               行动
         */
        OutputTag<String> displayTag = new OutputTag<String>("display") {};
        OutputTag<String> actionTag = new OutputTag<String>("action") {};
        OutputTag<String> errTag = new OutputTag<String>("err") {};
        OutputTag<String> pageTag = new OutputTag<String>("page") {};
        SingleOutputStreamOperator<String> start = stream.process(new ProcessFunction<JSONObject, String>() {
            
            
            @Override
            public void processElement(JSONObject obj,
                                       Context ctx,
                                       Collector<String> out) throws Exception {
                
                
                JSONObject start = obj.getJSONObject("start");
                
                if (start != null) {
                    out.collect(obj.toJSONString());
                    
                    
                } else {
                    JSONObject common = obj.getJSONObject("common");
                    JSONObject page = obj.getJSONObject("page");
                    Long ts = obj.getLong("ts");
                    // 其他日志
                    // 曝光
                    JSONArray displays = obj.getJSONArray("displays");
                    if (displays != null) {
                        // 把数组拍平了,再输出
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.putAll(common);
                            display.putAll(page);
                            display.put("ts", ts);
                            ctx.output(displayTag, display.toJSONString());
                        }
                        obj.remove("displays");  // 后面已经用不到displays, 所以删除
                    }
                    // 行动
                    JSONArray actions = obj.getJSONArray("actions");
                    if (actions != null) {
                        // 把数组拍平了,再输出
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.putAll(common);
                            action.putAll(page);
                            action.put("ts", ts);
                            ctx.output(actionTag, action.toJSONString());
                        }
                        obj.remove("actions");  // 后面已经用不到displays, 所以删除
                    }
                    //err
                    JSONObject err = obj.getJSONObject("err");
                    if (err != null) {
                        ctx.output(errTag, obj.toJSONString());
                        
                        obj.remove("err");
                    }
                    // page
                    if (obj.getJSONObject("page") != null) {
                        ctx.output(pageTag, obj.toString());
                    }
                }
            }
        });
        
        HashMap<String, DataStream<String>> map = new HashMap<>();
        
        map.put(START, start);
        map.put(DISPLAY, start.getSideOutput(displayTag));
        map.put(ACTION, start.getSideOutput(actionTag));
        map.put(ERR, start.getSideOutput(errTag));
        map.put(PAGE, start.getSideOutput(pageTag));
        
        
        return map;
    }
    
    private SingleOutputStreamOperator<JSONObject> validateNewOrOld(SingleOutputStreamOperator<JSONObject> stream) {
        return stream
            .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
            .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
                
                private ValueState<String> firstVisitDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisitDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject common = obj.getJSONObject("common");
                    String isNew = common.getString("is_new");
                    
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.toDate(ts);
                    
                    
                    String firstVisitDate = firstVisitDateState.value();
                    if ("1".equals(isNew)) {
                        if (firstVisitDate == null) {
                            // 一个新用户, 状态还是null, 娶确实是新用户
                            firstVisitDateState.update(today);
                        } else if (!today.equals(firstVisitDateState.value())) {
                            // 与第一次访问的日期不等, 表示这个新用户是错误, 有可能是app重装导致
                            // 今天不是第一次登录
                            common.put("is_new", "0");
                        }
                        
                    } else if (firstVisitDate == null) {  // 如果是老用户, 并且还没有状态, 把日期更新为昨天
                        String yesterday = AtguiguUtil.toYesterday(ts);
                        firstVisitDateState.update(yesterday);
                    }
                    out.collect(obj);
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream
            .filter(new FilterFunction<String>() {
                @Override
                public boolean filter(String value) throws Exception {
                    
                    try {
                        JSON.parseObject(value);
                    } catch (Exception e) {
                        System.out.println("json格式有问题....");
                        return false;
                    }
                    return true;
                }
            })
            .map(JSON::parseObject);
    }
}
